// pages/teacher/upload-file/index.js
import { Serve } from '../../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    class_id: '',
    // 选择班级下标
    index: -1,
    path: {},
    classes: [],
    alias: '',
    name: ''
  },

  handleAliasChange(e) {
    this.setData({ alias: e.detail.value })
  },

  handleClassChange(e) {
    const { classes } = this.data
    const index = e.detail.value
    const class_id = classes[index]._id
    this.setData({ index: e.detail.value, class_id })
  },

  handleNameInput(e) {
    this.setData({ name: e.detail.value })
  },

  async chooseFile(e) {
    const isEqualString = (str1, str2) => {
      return str1.toLowerCase() === str2.toLowerCase()
    }
    const result = await wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extensions: ['doc', 'docx']
    })
    
    const file = result.tempFiles[0]
    const arr = file.path.split('.')
    // 取后缀
    const suffix = arr[arr.length - 1]
    if (!isEqualString(suffix, 'doc') && !isEqualString(suffix, 'docx')) {
      wx.showToast({ title: '请上传word文件', icon: 'error', mask: true, duration: 800 })
      return 0
    }

    this.setData({ path: result.tempFiles[0] })
  },

  async confirmPublish() {
    const { class_id, alias, path, name, index, classes } = this.data
    if (!class_id) {
      wx.showToast({ title: '请选择班级', icon: 'error', mask: true, duration: 800 })
      return 0
    }
    if (!name) {
      wx.showToast({ title: '请输入题目名称', icon: 'error', mask: true, duration: 800 })
      return 0
    }
    if (JSON.stringify(path).length == 2) {
      wx.showToast({ title: '请上传文件', mask: true, icon: 'error', duration: 800 })
      return 0
    }
    // 标识为实验题目
    const has_file = true
    // 取班级名称
    const class_name = classes[index].name
    const _id = Math.random().toString(32).substring(2, 10).toUpperCase()
    const openid = wx.getStorageSync('openid')
    const arr = path.name.split('.')
    const suffix = arr[arr.length - 1]
    const filename = path.name
    wx.showLoading({ title: '请耐心等待', mask: true })
    const uploadResult = await wx.cloud.uploadFile({
      cloudPath: `${openid}/files/${path.name}`,
      filePath: path.path
    })
    const { fileID } = uploadResult
    await Serve.AddFile({ path: fileID, alias, class_id, test_id: _id, suffix, filename })
    await Serve.AddTest({ class_id, class_name, has_file, _id, name })
    wx.showToast({ title: '发布成功', icon: 'success', mask: true })
    wx.switchTab({ url: '/pages/home/index' })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    wx.showLoading({ title: '获取用户班级信息', mask: true })
    const classes = await Serve.GetClasses(2)
    wx.hideLoading()
    this.setData({ classes })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})